from src.business.db_manager import db_manager
from src.data.storage import PasswordStorage
from src.logger import logger
from src.business.db_manager import db_manager
from src.business.crypto_utils import crypto_utils
import threading
import requests
import json
from typing import Dict, List, Tuple, Optional

class AppController:
    """应用程序控制器，协调UI和业务逻辑之间的交互"""
    
    def __init__(self):
        """初始化控制器"""
        # 使用业务逻辑层的数据库管理器
        self.db_manager = db_manager
        # 数据访问层
        self.storage = PasswordStorage()
        # 用于回调的UI引用
        self.ui_callback = None
    
    def set_ui_callback(self, callback):
        """设置UI回调函数"""
        self.ui_callback = callback
    
    def add_connection(self, name: str, host: str, port: str, username: str, password: str) -> bool:
        """添加新的数据库连接"""
        return self.db_manager.add_connection(name, host, port, username, password)
    
    def get_connection(self, name: str) -> Optional[Dict[str, str]]:
        """获取连接配置"""
        return self.db_manager.get_connection(name)
    
    def list_connections(self) -> list:
        """列出所有连接"""
        return self.db_manager.list_connections()
    
    def delete_connection(self, name: str) -> bool:
        """删除连接"""
        return self.db_manager.delete_connection(name)
    
    def test_connection(self, name: str) -> Tuple[bool, str]:
        """测试连接是否可用"""
        return self.db_manager.test_connection(name)
    
    def get_databases(self, name: str) -> Tuple[bool, List[str] or str]:
        """获取数据库列表"""
        return self.db_manager.get_databases(name)
    
    def get_tables(self, name: str, database: str) -> Tuple[bool, List[str] or str]:
        """获取指定数据库中的表列表"""
        return self.db_manager.get_tables(name, database)
        
    def get_table_structure(self, name: str, database: str, table: str) -> Tuple[bool, List[Dict] or str]:
        """获取指定表的结构信息"""
        return self.db_manager.get_table_structure(name, database, table)
        
    def get_table_create_sql(self, name: str, database: str, table: str) -> Tuple[bool, str]:
        """获取指定表的建表SQL语句
        
        Args:
            name: 连接名称
            database: 数据库名称
            table: 表名称
        
        Returns:
            Tuple[bool, str]: (是否成功, 建表SQL语句或错误信息)
        """
        return self.db_manager.get_table_create_sql(name, database, table)
    
    def execute_query(self, name: str, database: str, query: str) -> Tuple[bool, List[Dict] or str, List[str] or None]:
        """执行SQL查询"""
        return self.db_manager.execute_query(name, database, query)
    
    def execute_query_in_thread(self, name: str, database: str, query: str, on_complete):
        """在后台线程中执行查询"""
        def execute():
            try:
                success, results, columns = self.db_manager.execute_query(name, database, query)
                if self.ui_callback:
                    self.ui_callback(lambda: on_complete(success, results, columns))
            except Exception as e:
                logger.error(f"查询执行异常: {e}")
                if self.ui_callback:
                    self.ui_callback(lambda: on_complete(False, f"查询执行异常: {str(e)}", None))
        
        # 创建并启动线程
        thread = threading.Thread(target=execute)
        thread.daemon = True
        thread.start()
    
    def check_for_updates_in_thread(self, current_version: str, on_complete):
        """在后台线程中检查更新"""
        def check():
            try:
                # 这里是模拟版本检查逻辑
                # 在实际应用中，应该从远程服务器获取最新版本信息
                logger.info(f"检查更新，当前版本: {current_version}")
                # 模拟网络延迟
                import time
                time.sleep(2)
                
                # 假设最新版本与当前版本相同
                latest_version = "1.0.0"
                is_newer = False  # 模拟没有新版本
                
                if self.ui_callback:
                    self.ui_callback(lambda: on_complete(current_version, latest_version, is_newer))
            except Exception as e:
                logger.error(f"检查更新异常: {e}")
                if self.ui_callback:
                    self.ui_callback(lambda: on_complete(current_version, None, False, str(e)))    
                    
    def check_for_updates(self, callback):
        """检查应用程序更新，通过HTTP请求连接到passserver"""
        current_version = "1.0.0"  # 当前应用版本 (保持与gui.py中一致的格式)
        
        def check():
            try:
                logger.info(f"正在检查更新，当前版本: {current_version}")
                
                # 使用对称密钥加密clientVersion参数
                encryption_key = "20250918"
                encrypted_version = crypto_utils.encrypt(current_version, encryption_key)
                logger.info(f"版本加密完成: {encrypted_version}")
                
                # 调用passserver项目中的/update/check接口
              #  update_server_url = "http://localhost:8082/update/check"
                update_server_url = "http://localhost:8082/update/mapcheck"
                params = {"clientVersion": encrypted_version}
                
                # 发送GET请求
                response = requests.get(update_server_url, params=params, timeout=5)
                
                if response.status_code == 200:
                    # 解析响应数据
                    update_info = response.json()
                    latest_version = update_info.get("latestVersion", current_version)
                    need_update = update_info.get("needUpdate", False)
                    
                    logger.info(f"更新检查完成，最新版本: {latest_version}, 需要更新: {need_update}")
                    
                    if need_update:
                        callback(True, "发现新版本", current_version, latest_version)
                    else:
                        callback(True, "当前已是最新版本", current_version, latest_version)
                else:
                    logger.warning(f"更新检查请求失败，状态码: {response.status_code}")
                    callback(False, f"更新检查请求失败，状态码: {response.status_code}", current_version, current_version)
                    
            except requests.exceptions.ConnectionError:
                logger.error(f"无法连接到更新服务器")
                callback(False, "无法连接到更新服务器", current_version, current_version)
            except requests.exceptions.Timeout:
                logger.error(f"更新服务器响应超时")
                callback(False, "更新服务器响应超时", current_version, current_version)
            except Exception as e:
                logger.error(f"更新检查异常: {e}")
                callback(False, f"更新检查异常: {str(e)}", current_version, current_version)
        
        # 创建并启动线程
        thread = threading.Thread(target=check)
        thread.daemon = True
        thread.start()

# 创建一个全局的应用控制器实例
app_controller = AppController()